package com.serviceprovider.business.module.admin.role.services.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.role.model.RoleHierarchy;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IReloadableRoleHierarchy;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IRoleHierarchyService;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IRoleService;

import org.springframework.security.userdetails.hierarchicalroles.RoleHierarchyImpl;

//~--- JDK imports ------------------------------------------------------------

import java.io.Serializable;

import java.util.List;

public class DBDrivenRoleHierarchy extends RoleHierarchyImpl implements IReloadableRoleHierarchy, Serializable {
    private IRoleHierarchyService roleHierarchyService;
    private IRoleService          roleService;

    public IRoleHierarchyService getRoleHierarchyService() {
        return roleHierarchyService;
    }

    public void setRoleHierarchyService(IRoleHierarchyService roleHierarchyService) {
        this.roleHierarchyService = roleHierarchyService;
    }

    public IRoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    public void reloadHierarchy() {
        StringBuffer s = new StringBuffer();    // s is used to store roleHierarchyStringRepresentation , @see RoleHierarchyImpl#setHierarchy
        List<RoleHierarchy> hList = roleHierarchyService.findAll();

        for (RoleHierarchy h : hList) {
            String role1 = roleService.getRoleById(h.getRole1()).getName();
            String role2 = roleService.getRoleById(h.getRole2()).getName();

            s.append(role1).append(h.getSign()).append(role2);
            s.append("\n");
        }

        String hierarchyString = (s.length() == 0)
                                 ? ""
                                 : s.substring(0, s.length() - 1);

        setHierarchy(hierarchyString);
    }

    @Override
    public void setHierarchy(String roleHierarchyStringRepresentation) {
        if ((roleHierarchyStringRepresentation != null) && roleHierarchyStringRepresentation.equals("reload")) {
            reloadHierarchy();
        } else {
            super.setHierarchy(roleHierarchyStringRepresentation);
        }
    }
}



